package repositories

import (
	"new_ginblog/internal/db"
	"new_ginblog/internal/middleware"
	"new_ginblog/internal/models"
	"new_ginblog/internal/utils/errormsg"
)

// AddArticle 增加文章
func AddArticle(article *models.Article) int {
	err := db.DB.Create(&article).Error
	if err != nil {
		middleware.SugarLogger.Error(err.Error())
		return errormsg.ERROR
	}
	return errormsg.SUCCESS
}

// GetArticle 获取指定文章
func GetArticle(id int) (models.Article, int) {
	var article models.Article
	err := db.DB.Where("id = ?", id).First(&article).Error
	if err != nil {
		return article, errormsg.ERROR
	}
	return article, errormsg.SUCCESS
}

// GetArticleList 获取分类下的全部文章
func GetArticleList(cid, pageSize, pageNum int) ([]models.Article, string, int, int64) {
	var articleList []models.Article
	var total int64
	var category string
	if err := db.DB.Where("id = ?", cid).First(&models.Category{}).Error; err != nil {
		return nil, category, 0, errormsg.ERROR // 分类不存在或查询失败
	}

	err := db.DB.Preload("Category").Limit(pageSize).Offset((pageNum-1)*pageSize).Where("cid = ?", cid).Find(&articleList).Count(&total).Error
	if err != nil {
		return nil, category, errormsg.ERROR, 0
	}
	return articleList, category, errormsg.SUCCESS, total
}

// DeleteArticle 删除文章
func DeleteArticle(id int) int {
	var article models.Article
	err := db.DB.Where("id = ?", id).Delete(&article).Error
	if err != nil {
		return errormsg.ERROR
	}
	return errormsg.SUCCESS
}

// UpdateArticle 修改文章
func UpdateArticle(id int, user *models.Article) int {
	err := db.DB.Model(&models.Article{}).Where("id = ?", id).Updates(&user).Error
	if err != nil {
		return errormsg.ERROR
	}
	return errormsg.SUCCESS
}
